/**
 * 
 */
package com.gragra.dataHandling;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
/**
 * @author Christoph Teichmann
 * created Oct 30, 2013 5:53:49 PM
 * @version 0.1
 */
public class MergeTables
{
	/**
	 *
	 * @param args
	 */
	public static void main(String[] args) throws IOException
	{
		int position = Integer.parseInt(args[0]);
		String outFile = args[1];
		String[] fileNames = Arrays.copyOfRange(args, 2, args.length);
		ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
		for (int i = 0; i < fileNames.length; i++)
		{
			BufferedReader br = new BufferedReader(new FileReader(fileNames[i]));
			br.readLine();
			int k = 0;
			String line;
			while((line = br.readLine()) != null)
			{
				String[] parts = line.split(",");
				if(list.size()<=k)
				{
					list.add(new ArrayList<String>());
					list.get(k).add(Integer.toString(k+1));
				}
				ArrayList<String> l = list.get(k);
				l.add(parts[position]);
				++k;
			}
			br.close();
		}
		BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
		reduce(fileNames);
		write(fileNames,out);
		for (ArrayList<String> strings : list)
		{
			out.newLine();
			write(strings, out);
		}
		out.close();
	}
	/**
	 *
	 * @param strings
	 * @param out
	 * @throws IOException 
	 */
	private static void write(ArrayList<String> strings, BufferedWriter out) throws IOException
	{
		for (int i = 0; i < strings.size(); i++)
		{
			String string = strings.get(i);
			if(i!=0)
			{out.write(",");}
			out.write(string);
		}
	}
	/**
	 *
	 * @param fileNames
	 */
	private static void reduce(String[] fileNames)
	{
		for (int i = 0; i < fileNames.length; i++)
		{
			String string = fileNames[i];
			String[] parts = string.split("/");
			fileNames[i] = parts[parts.length-1];
		}
	}
	/**
	 *
	 * @param fileNames
	 * @param out
	 * @throws IOException 
	 */
	private static void write(String[] fileNames, BufferedWriter out) throws IOException
	{
		out.write("Iteration");
		for (int i = 0; i < fileNames.length; i++)
		{
			String string = fileNames[i];
			out.write(",");
			out.write(string);
		}
	}
}